﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Moop.UI.Exceptions;

namespace Moop.UI.Utils
{
    public static class UIUtils
    {
        public static FlattenedAggregateException HadleAggregateException(this AggregateException ex)
        {
            Exception inner = null;
            FlattenedAggregateException flatAggEx = new FlattenedAggregateException();

            if (string.IsNullOrEmpty(ex.StackTrace))
                inner = ex.InnerExceptions.FirstOrDefault();

            if (inner != null)
                flatAggEx.Message = inner.Message; flatAggEx.StackTrace = inner.StackTrace;

            return flatAggEx;
        }

        public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
        {
            HashSet<TKey> seenKeys = new HashSet<TKey>();
            foreach (TSource element in source)
            {
                if (seenKeys.Add(keySelector(element)))
                {
                    yield return element;
                }
            }
        }
    }
}
